package cn.itsource.pet.service.impl;

import cn.itsource.pet.domain.PetType;
import cn.itsource.pet.mapper.PetTypeMapper;
import cn.itsource.pet.service.IPetTypeService;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mochen
 * @since 2023-01-31
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> getTree() {
        List<PetType> all = petTypeMapper.loadAll();
        List<PetType> result = new ArrayList<>();

        /*宠物集合转成map,map'k = id;map'v = 类型对象*/
        Map<Long, PetType> map = new HashMap<>();
        for (PetType petType : all) {
            map.put(petType.getId(),petType);
        }

        for (PetType petType : all) {
            if (petType.getPid() == null){
                result.add(petType);
            }else {
                PetType parent = map.get(petType.getPid());
                List<PetType> children = parent.getChildren();
                children.add(petType);
            }
        }
        return result;
    }
}
